import json
from flask import Flask, render_template
from flask_socketio import SocketIO
from kafka import KafkaConsumer


app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None
consumer = KafkaConsumer(
    auto_offset_reset='earliest',
    bootstrap_servers = "niit01:9092",
    group_id = "niit2",
    )
consumer.subscribe(["result3"])

def background_thread():
    inschool = 0
    outschool = 0
    #在籍:inschool
    #不在籍:outschool
    # 'A' 5
    # 'L' 3
    for msg in consumer:
        data_json = msg.value.decode('utf8')
        print('-----当前数据----'+ data_json )
        #  解析json数据
        # data_list = json.loads(data_json)
        obj = data_json.split(',')
        if 'A' in msg.value.decode('utf8'):
            inschool = obj[1]
        elif 'L' in msg.value.decode('utf8'):
            outschool = obj[1]
        else:
            continue
        result = str(inschool) + ',' + str(outschool)
        print(result)
        socketio.emit('test_message',{'data':result})


@socketio.on('test_connect')
def connect(message):
    print(message)
    global thread
    if thread is None:
        thread = socketio.start_background_task(target=background_thread)
    socketio.emit('connected', {'data': 'Connected'})


@app.route("/")
def handle_mes():
    return render_template("index1.html")


if __name__ == '__main__':
    socketio.run(app,debug=True)